/**
 * @FileName: PermissionTree.java
 * @Author
 * @Description:
 * @Date 2015年12月24日 下午1:52:34
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.role;

import java.util.ArrayList;
import java.util.List;

import cn.hpclub.server.model.Permission;
import cn.hpclub.server.model.SysRolePermission;

public class PermissionTree{
    private static final int LEAF_NODE = 2;

    public static PermissionNode getPermissionNodeTree(int adminRole){
        List<Permission> permList = Permission.dao.getPermission(adminRole);
        List<Integer> selectedPermIdList = new ArrayList<Integer>();
        PermissionNode root = parsePermsNodeTree(permList, selectedPermIdList);
        root.printNodes("");
        return root;
    }

    public static PermissionNode getPermissionNodeTreeForEdit(int adminRole, int roleId){
        List<Permission> permList = Permission.dao.getPermission(adminRole);
        List<Integer> selectedPermIdList = SysRolePermission.dao.getPermissionIds(roleId);
        PermissionNode root = parsePermsNodeTree(permList, selectedPermIdList);
        root.printNodes("");
        return root;
    }

    private static PermissionNode parsePermsNodeTree(List<Permission> permList, List<Integer> selectedPermIdList){
        PermissionNode root = new PermissionNode();
        for(int i = 0; i < permList.size(); i++){
            Permission perms = permList.get(i);
            PermissionNode subNode = getPermNode(perms);
            if(selectedPermIdList.contains(subNode.getId())){
                subNode.setSelected(true);
            }
            if(subNode.getParentId() == 0){
                root = subNode;
            } else{
                PermissionNode node = findParentNode(root, subNode.getParentId());
                if(node != null){
                    node.addSubNode(subNode);
                }
            }
        }
        return root;
    }

    private static PermissionNode getPermNode(Permission perms){
        PermissionNode subNode = new PermissionNode();
        subNode.setId(perms.getInt("id"));
        subNode.setName(perms.getStr("name"));
        subNode.setParentId(perms.getInt("parent_id"));
        subNode.setLevel(perms.getInt("level"));
        Integer type = perms.getInt("type");
        if(LEAF_NODE == type){
            subNode.setLeafNode(true);
        } else{
            subNode.setLeafNode(false);
        }
        return subNode;
    }

    private static PermissionNode findParentNode(PermissionNode node, int nodeId){
        if(node == null){
            return null;
        }
        if(node.getId() == nodeId){
            return node;
        }
        if(node.getSubNodes() == null){
            return null;
        }
        for(PermissionNode subNode : node.getSubNodes()){
            PermissionNode parentNode = findParentNode(subNode, nodeId);
            if(parentNode != null){
                return parentNode;
            }
        }
        return null;
    }
}
